import { ref } from "vue";
import { defineStore } from "pinia";
import { loginAPI } from "@/apis/user.js";
import { mergeCartAPI } from "@/apis/cart.js";
import { useCartStore } from "@/stores/cartStore.js";
import { updateNewList } from "@/apis/cart.js";
export const useUserStore = defineStore(
  "user",
  () => {
    // 用户的数据管理
    // state 用户数据
    const userInfo = ref({});
    // 登录 获取用户数据的方法
    const getuserInfo = async ({ account, password }) => {
      const useCart = useCartStore();
      const res = await loginAPI({ account, password });
      userInfo.value = res.result;
      // 登录成功后，合并购物车
      const items = useCart.cartList.map((item) => {
        return {
          skuId: item.skuId,
          selected: item.selected,
          count: item.count,
        };
      });
      await mergeCartAPI(items);
      // 更新数据
      useCart.updateNewCartList();
    };
    // 退出登录
    const clearUserInfo = () => {
      userInfo.value = {};
    };

    return {
      userInfo,
      getuserInfo,
      clearUserInfo,
    };
  },
  {
    // 持久化存储
    persist: {
      enabled: true,
    },
  }
);
